package boot.spring.service;

import boot.spring.config.LocalCache;
import boot.spring.consts.UserConstants;
import boot.spring.po.CMessage;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@ServerEndpoint("/webSocket/{username}")
@Component
public class WebSocketServer {
    private static final Logger logger = LoggerFactory.getLogger(WebSocketServer.class);
	 //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static AtomicInteger onlineNum = new AtomicInteger();

    //concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

    private boolean useContext = false;
    private static final String MUTIPLE_CONVER = "连续对话";
    private static final String SINGLE_CONVER = "单次对话";
    private static final String NEW_CONVER = "新对话";
    @OnMessage
    public void onMessage(String message) throws IOException{
        System.out.println("server get " + message);
        CMessage msg=JSON.parseObject(message, CMessage.class);
        String requestText = msg.getText();
        if (requestText.equals("1") || requestText.equals("2") || requestText.equals("3") || requestText.equals(MUTIPLE_CONVER) || requestText.equals(SINGLE_CONVER) || requestText.equals(NEW_CONVER)) {
            configConverCommand(requestText);
        } else {
            String replyText = ChatService.getInstance().ask(requestText);
            CMessage replyMsg = new CMessage();
            replyMsg.setFrom(getFromUserName());
            replyMsg.setText(replyText);
            replyMsg.setDate(new Date());
            sendInfo(UserConstants.USER_NAME, JSON.toJSONString(replyMsg,true));
        }
    }

    private void configConverCommand(String requestText) {
        CMessage replyMsg = new CMessage();
        replyMsg.setDate(new Date());
        if (requestText.equals(MUTIPLE_CONVER) || requestText.equals("1")) {
            useContext = true;
            replyMsg.setText("已设置为连续对话状态，会根据对话上下文回答");
        }
        if (requestText.equals(SINGLE_CONVER) || requestText.equals("2")) {
            useContext = false;
            LocalCache.CACHE.clear();
            replyMsg.setText("已设置为单次对话状态，不会根据对话上下文回答");
        }
        if (requestText.equals(NEW_CONVER) || requestText.equals("3")) {
            LocalCache.CACHE.clear();
            replyMsg.setText("已开启新会话，不再根据之前上下文回答");
        }
        replyMsg.setFrom(getFromUserName());
        sendInfo(UserConstants.USER_NAME, JSON.toJSONString(replyMsg,true));
    }

    private String getFromUserName() {
        return UserConstants.USER_NAME + (useContext ? "(连续对话)" : "(单轮对话)");
    }

    //发送消息
    public void sendMessage(Session session, String message) throws IOException {
        if(session != null){
            synchronized (session) {
                //System.out.println("发送数据：" + message);
                session.getBasicRemote().sendText(message);
            }
        }
    }
    //给指定用户发送信息
    public void sendInfo(String userName, String message){
        Session session = sessionPools.get(userName);
        try {
            sendMessage(session, message);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    // 群发消息
    public void broadcast(String message){
    	for (Session session: sessionPools.values()) {
            try {
                sendMessage(session, message);
            } catch(Exception e){
                e.printStackTrace();
                continue;
            }
        }
    }

    //建立连接成功调用
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "username") String userName){
        sessionPools.put(userName, session);
        addOnlineCount();
        System.out.println(userName + "加入webSocket！当前人数为" + onlineNum);
        //发送操作提示信息
        CMessage replyMsg = new CMessage();
        replyMsg.setFrom(getFromUserName());
        replyMsg.setText("内置指令:<br>(1)连续对话:进入连续对话状态(默认);<br>(2)单次对话:进入单次对话状态;<br>(3)新会话:开启新会话");
        replyMsg.setDate(new Date());
        sendInfo(UserConstants.USER_NAME, JSON.toJSONString(replyMsg,true));
//        // 广播上线消息
//        Message msg = new Message();
//        msg.setDate(new Date());
//        msg.setTo("0");
//        msg.setText(userName);
//        broadcast(JSON.toJSONString(msg,true));
    }

    //关闭连接时调用
    @OnClose
    public void onClose(@PathParam(value = "username") String userName){
        sessionPools.remove(userName);
        subOnlineCount();
        System.out.println(userName + "断开webSocket连接！当前人数为" + onlineNum);
        // 广播下线消息
        CMessage msg = new CMessage();
        msg.setDate(new Date());
        msg.setTo("-2");
        msg.setText(userName);
        broadcast(JSON.toJSONString(msg,true));
    }

    //错误时调用
    @OnError
    public void onError(Session session, Throwable throwable){
        System.out.println("发生错误");
        throwable.printStackTrace();
    }

    public static void addOnlineCount(){
        onlineNum.incrementAndGet();
    }

    public static void subOnlineCount() {
        onlineNum.decrementAndGet();
    }
    
    public static AtomicInteger getOnlineNumber() {
        return onlineNum;
    }
    
    public static ConcurrentHashMap<String, Session> getSessionPools() {
        return sessionPools;
    }
}
